<?php
namespace App\Http\Controllers\Admin;
use App\Http\Model\Article;
use App\Http\Model\Category;
use App\Http\Model\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;

class ArticleController extends CommonController{
    public function index(){
        $art_model = new Article();
        $data=$art_model->getArt();
        return view('admin.article.index')->with('data',$data);
    }

    public function changeOrder(){
        if($input=Input::all()){
           $cate = Category::find($input['cate_id']);
            $cate->cate_order=$input['num'];
            $re=$cate->update();
           if($re){
               $data['status']=1;
               $data['msg']='修改成功';
           }else{
               $data['status']=0;
               $data['msg']='修改失败';
           }
            return $data;
        }
    }
    public function create(){
        $cate = new Category();
        $data = $cate->tree();
        return view('admin.article.add')->with('data',$data);
    }

    public function store(Request $request){
        if($data = $request->except('_token')){
            $rules=array(
                'art_title'=>'required',
            );
            $msg=[
                'art_title.required'=>'文章标题不能为空',

            ];
            $validator =Validator::make($data,$rules,$msg);
            if($validator->passes()){
                $data['art_time'] = time();
                $re = Article::create($data);
                if($re){
                    return redirect('admin/article/create');
                }else{
                    return back()->with('errors','添加失败');
                }
            }else{
                return back()->withErrors($validator);
            }

        }
    }
    public function edit($id){
        $cate = new Category();
        $category = $cate->tree();
        $art = new Article();
        $data = $art->getArticle($id);
        return view('admin.article.edit',compact('data','category'));
    }
    public function update($id){
        if($input= Input::except('_token','_method','file_upload')){
            $re = Article::where('art_id',$id)->update($input);
            if($re){
                return redirect('admin/article');
            }else{
                return back()->with('errors','编辑失败');
            }
        }

    }
    public function destroy($id){

        $re = Article::where('art_id',$id)->delete();
        if($re){
            $data=[
                'status'=>1,
                'msg'=>'删除成功'
            ];
        }else{
            $data=[
                'status'=>0,
                'msg'=>'删除失败'
            ];
        }
        return $data;
    }
}